<template>
  <el-dialog
    @close="close"
    title="新增目录"
    width="20%"
    :visible.sync="dialogVisible"
  >
    <div>
      <el-form
        label-width="80px"
        :model="formData"
        :rules="formRules"
        ref="from"
      >
        <el-form-item v-show="!id" label="所属学科" prop="subjectName">
          <el-select v-model="formData.subjectID" placeholder="请选择">
            <el-option
              v-for="item in list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目录名称" prop="directoryName">
          <el-input
            size="small"
            v-model="formData.directoryName"
            placeholder="请输入目录名称"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>

    <div slot="footer">
      <el-button size="small" @click="close">取 消</el-button>
      <el-button size="small" type="primary" @click="btnOK">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { dsubjectApi } from "@/api/subject";
import { adddirectorysApi, editdirectorysApi } from "@/api/directorys";
export default {
  data() {
    return {
      dialogVisible: false,
      list: [],

      formData: {
        subjectID: "",
        directoryName: "",
      },
      formRules: {
        directoryName: [{ required: true, message: "请输入", trigger: "blur" }],
      },
    };
  },

  created() {
    this.initData();
  },
  props: {
    id: {
      type: String,
      required: true,
    },
  },

  methods: {
    async initData() {
      let res = await dsubjectApi();
      console.log(res);
      this.list = res;
    },
    async btnOK() {
      try {
        await this.$refs.from.validate();
      } catch (error) {
        console.log(error);
      }
      if (this.formData.id) {
        // 修改
        await editdirectorysApi(this.formData);
        this.$message.success("修改成功");
      } else {
        if (this.id) {
          await adddirectorysApi({
            directoryName: this.formData.directoryName,
            subjectID: parseInt(this.id),
          });
        } else {
          // 发起添加请求
          await adddirectorysApi({
            directoryName: this.formData.directoryName,
            subjectID: this.formData.subjectID,
          });
        }

        // 提示
        this.$message.success("添加成功");
      }

      this.dialogVisible = false;
      this.formData = {};
      this.$emit("btnK");
    },
    close() {
      this.dialogVisible = false;
      this.formData = {};
    },
  },
};
</script>

<style lang='less' scoped>
/deep/.el-dialog {
  border-radius: 8px;
  .el-dialog__header {
    border-radius: 8px 8px 0px 0px;
  }
  .el-dialog__close {
    color: #fff;
  }
}
</style>